package com.example.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

/**
 * @author void
 * @date 2021/1/5 15:05
 * @desc
 */
@Component
public class MyAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
    
    @Autowired
    private UserDetailsService myUserDetailService;

    /**
     * 附加认证过程
     * @param userDetails
     * @param authentication
     * @throws AuthenticationException
     */
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        
        if(authentication.getCredentials()==null){
            throw new BadCredentialsException(this.messages.getMessage(
                    "MyAuthenticationProvider.additionalAuthenticationChecks", "密码不能为空"));
        }else{
            String presentedPassword = authentication.getCredentials().toString();
            if(!presentedPassword.equals(userDetails.getPassword())){
                throw new BadCredentialsException(this.messages.getMessage(
                        "MyAuthenticationProvider.additionalAuthenticationChecks", "密码错误"));
            }
        }
    }

    /**
     * 检索用户
     * @param username
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        return myUserDetailService.loadUserByUsername(username);
    }
}
